package com.tjetc.service.Impl;

import com.tjetc.dao.*;
import com.tjetc.entity.CollectShop;
import com.tjetc.entity.Merchant;
import com.tjetc.service.CollectShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CollectShopServiceImpl implements CollectShopService {
    @Autowired
    private CollectShopMapper collectShopMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private OrderMapper orderMapper;

    /***
     * 添加收藏的店铺
     * @param collectShop
     * @return
     */
    @Override
    public int addShop(CollectShop collectShop) {
        return collectShopMapper.addShop(collectShop);
    }

    /***
     * 删除收藏的店铺
     * @param userId
     * @param merchantId
     * @return
     */
    @Override
    public int deleteShop(Integer userId,Integer merchantId) {
        return collectShopMapper.deleteShop(userId,merchantId);
    }

    /***
     * 根据用户id查询收藏店铺的列表
     * @param id
     * @return
     */
    @Override
    public List<Merchant> selectByUserId(Integer id) {
        List<CollectShop> collectShops = collectShopMapper.selectByUserId(id);
        //获取收藏所有店铺的id
        List<Integer> ids=new ArrayList<>();
        for(int i=0;i<collectShops.size();i++){
            ids.add(collectShops.get(i).getMerchantId());
        }
        //批量搜索店家的信息
        List<Merchant> merchants=merchantMapper.selectMerchantByList(ids);
        return merchants;
    }

    /***
     * 查询该店铺是否被该用户收藏
     * @param userId
     * @param merchantId
     * @return
     */
    @Override
    public CollectShop queryCollect(int userId, int merchantId) {
        return collectShopMapper.queryCollect(userId, merchantId);
    }

    /***
     * 获取制定时间，制定id的店家的总单数
     * @param MerchantId
     * @return
     */
    @Override
    public Integer getMonthlyOrderNums(Integer MerchantId) {
        LocalDateTime end=LocalDateTime.now();
        LocalDateTime start=end.minusMonths(1);
        System.out.println();
        int monthlyOrderNums = (int)orderMapper.getMonthlyOrderNums(start, end, MerchantId);
        return monthlyOrderNums;
    }

    /***
     * 获取制定时间，制定id的店家的总金额
     * @param MerchantId
     * @return
     */
    @Override
    public BigDecimal getMonthlyOrderAmount(Integer MerchantId) {
        LocalDateTime end=LocalDateTime.now();
        LocalDateTime start=end.minusMonths(1);
        BigDecimal monthlyOrderAmount = (BigDecimal)orderMapper.getMonthlyOrderAmount(start, end, MerchantId);
        Integer monthlyOrderNums = (int)orderMapper.getMonthlyOrderNums(start, end, MerchantId);
        if(monthlyOrderNums==0){
            return new BigDecimal(0);
        }
        BigDecimal result = monthlyOrderAmount.divide(new BigDecimal(monthlyOrderNums),BigDecimal.ROUND_CEILING);
        return result;
    }
}
